import { IHttpResponse } from '@ibiz-template/core';
import { SearchBarService } from '@ibiz-template/runtime/out/controller/control/search-bar/search-bar.service';

/**
 * 搜索栏服务
 */
export class FilterSearchBarService extends SearchBarService {
  /**
   * 新建分组
   * @param group
   * @returns
   */
  async createGroup(group: IData): Promise<IHttpResponse> {
    const [createParams] = this.convertFrontDataToBack([group]);
    const res = await this.app.net.post(`${this.themeUrl}`, createParams);
    return res;
  }

  /**
   * 转换后台数据成前端需要的格式
   * @param data
   * @returns
   */
  convertBackDataToFront(data: IData[]): IData[] {
    return data.map(item => {
      const tempItem = { ...item };
      if (item.theme_model) {
        tempItem.filter = JSON.parse(item.theme_model);
      }
      tempItem.collect = item.valid_flag === 1;
      if (item.order_value) {
        tempItem.order = item.order_value;
      }
      return tempItem;
    });
  }

  /**
   * 转换前端数据成后台需要的格式
   * @param data
   * @returns
   */
  convertFrontDataToBack(data: IData[]): IData[] {
    return data.map(item => {
      const tempItem: IData = {
        ...item,
        app_tag: this.model.appId,
        app_view_tag: this.viewTag,
      };
      if (item.filter) {
        tempItem.theme_model = JSON.stringify(item.filter);
      }
      tempItem.valid_flag = item.collect ? 1 : 0;
      if (item.order) {
        tempItem.order_value = item.order;
      }
      return tempItem;
    });
  }
}
